from rest_framework import serializers
import json, datetime, logging, requests, math
from random import randint
from django_redis import get_redis_connection
from django.db.models import Count, Sum, Max, Min, Avg, Q, F

from equity_admin.filters_merchants import *
from activities.models import *
from businesses.models import *
from goods.models import *
from cashbonus.models import *
from vouchers.models import *
from users.models import *
from equity_mall.utils.utils import check_sign_contract_result, get_sign_contract_url, random_str
from equity_mall.utils.sync_img_to_local import make_qrcode1, sync_img_to_local, make_qrcode4, make_qrcode5
from equity_mall.utils.qiniu_storage import pic_delete

logger = logging.getLogger('django')


class CashActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    activity_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    mchid = serializers.SerializerMethodField(read_only=True)
    city_name = serializers.SerializerMethodField(read_only=True)
    district_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'create_time', 'mobile', 'state', 'state_str', 'received_time', 'customeruser_realname', 'companyuser_nickname', 'activity_name',
                  'activity_type', 'activity_type_str', 'level_name', 'amount', 'expired_time', 'payment_no', 'cash_activity_id', 'return_msg', 'mchid', 'payeeFullName',
                  'city_name', 'district_name']

    def get_city_name(self, obj):
        try:
            return obj.level.city_name
        except:
            return ''

    def get_district_name(self, obj):
        try:
            return obj.level.district_name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_mchid(self, obj):
        try:
            channel = obj.channel
            if channel:
                return f'{channel.name}({channel.mchid})'
            else:
                return ''
            # if obj.mchid == '1486198522':
            #     return '信翔商户(1486198522)'
            # elif obj.mchid == '1571060401':
            #     return '信亨商户(1571060401)'
            # elif obj.mchid == 'wx':
            #     return '信翔商户(1486198522)'
            # elif obj.mchid == 'alipay':
            #     return '信翔支付宝服务商(2088631976752358)'
            # else:
            #     return ''
        except:
            return ''

    def get_activity_type_str(self, obj):
        try:
            return obj.cash_activity.get_activity_type_display()
        except:
            return ''

    def get_activity_type(self, obj):
        try:
            return obj.cash_activity.activity_type
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            return obj.customer_user.realname
        except:
            return ''

    def get_mobile(self, obj):
        try:
            if obj.customer_user:
                return obj.customer_user.mobile
            elif obj.customeruservice:
                return obj.customeruservice.mobile
            else:
                return obj.mobile
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''


class MerchantUserListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_psbc_card_str = serializers.CharField(source='get_is_psbc_card_display', read_only=True)

    class Meta:
        model = MerchantUser
        fields = ['id', 'mobile', 'openid', 'create_time', 'is_psbc_card', 'is_psbc_card_str', 'lucky_bag']


class MerchantUserRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_psbc_card_str = serializers.CharField(source='get_is_psbc_card_display', read_only=True)

    class Meta:
        model = MerchantUser
        fields = ['id', 'mobile', 'openid', 'create_time', 'is_psbc_card', 'is_psbc_card_str', 'lucky_bag']


class LuckyBagActivityListModelSerializer(serializers.ModelSerializer):

    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)

    class Meta:
        model = LuckyBagActivity
        fields = ['id', 'activity_name', 'activity_status', 'activity_status_str', 'available_begin_time', 'available_end_time', 'description', 'explain']


class LuckyBagChildActivityListModelSerializer(serializers.ModelSerializer):

    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)

    class Meta:
        model = LuckyBagChildActivity
        fields = ['id', 'activity_type', 'activity_type_str', 'description', 'limit_time_description', 'limit_day_description', 'banner']


class LuckyBagActivityRetrieveModelSerializer(serializers.ModelSerializer):

    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    child_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LuckyBagActivity
        fields = ['id', 'activity_name', 'activity_status', 'activity_status_str', 'available_begin_time', 'available_end_time', 'description', 'explain', 'child_set']

    def get_child_set(self, obj):
        child_set = obj.luckybagchildactivity_set.all()
        return LuckyBagChildActivityListModelSerializer(child_set, many=True).data


class LuckyBagChildActivityDataListModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    lucky_status_str = serializers.CharField(source='get_lucky_status_display', read_only=True)
    activity_type_str = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    level_data = serializers.SerializerMethodField(read_only=True)
    merchant_data = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LuckyBagChildActivityData
        fields = ['id', 'business_no', 'lucky_bag', 'lucky_status_str', 'lucky_status', 'received_time', 'activity_type_str', 'luckybagchildactivity_id',
                  'mobile', 'merchantuser_id', 'activity_type', 'level_data', 'merchant_data']

    def get_level_data(self, obj):
        data = {}
        data['name'] = ''
        data['account'] = ''
        try:
            level = obj.level
            data['name'] = level.name
            data['account'] = level.account
        except:
            pass
        return data

    def get_merchant_data(self, obj):
        data = {}
        data['id'] = ''
        data['business_no'] = ''
        data['name'] = ''
        try:
            merchant = Merchant.objects.get(wyfMerchantID=obj.business_no)
            data['id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
            data['name'] = merchant.name
        except:
            pass
        return data

    def get_activity_type_str(self, obj):
        return obj.luckybagchildactivity.get_activity_type_display()

    def get_activity_type(self, obj):
        return obj.luckybagchildactivity.activity_type

    def get_mobile(self, obj):
        try:
            return obj.merchantuser.mobile
        except:
            return ''


class LuckyBagChildActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    lucky_status_str = serializers.CharField(source='get_lucky_status_display', read_only=True)
    activity_type_str = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    level_data = serializers.SerializerMethodField(read_only=True)
    merchant_data = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LuckyBagChildActivityData
        fields = ['id', 'business_no', 'lucky_bag', 'lucky_status_str', 'lucky_status', 'received_time', 'activity_type_str', 'luckybagchildactivity_id',
                  'mobile', 'merchantuser_id', 'activity_type', 'level_data', 'merchant_data']

    def get_level_data(self, obj):
        data = {}
        data['name'] = ''
        data['account'] = ''
        try:
            level = obj.level
            data['name'] = level.name
            data['account'] = level.account
        except:
            pass
        return data

    def get_merchant_data(self, obj):
        data = {}
        data['id'] = ''
        data['business_no'] = ''
        data['name'] = ''
        try:
            merchant = Merchant.objects.get(wyfMerchantID=obj.business_no)
            data['id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
            data['name'] = merchant.name
        except:
            pass
        return data

    def get_activity_type_str(self, obj):
        return obj.luckybagchildactivity.get_activity_type_display()

    def get_activity_type(self, obj):
        return obj.luckybagchildactivity.activity_type

    def get_mobile(self, obj):
        try:
            return obj.merchantuser.mobile
        except:
            return ''


class LuckyBagRecordListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    operate_type_str = serializers.CharField(source='get_operate_type_display', read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    merchant_data = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LuckyBagRecord
        fields = ['id', 'lucky_bag', 'operate_type_str', 'operate_type', 'create_time', 'lucky_bag_balance',
                  'mobile', 'merchantuser_id', 'merchant_data']

    def get_merchant_data(self, obj):
        data = {}
        data['business_no'] = ''
        data['account'] = ''
        data['merchant_name'] = ''
        data['level_name'] = ''
        try:
            if obj.operate_type == 1:
                activitydata = obj.activitydata
                business_no = activitydata.business_no
                merchant = Merchant.objects.get(wyfMerchantID=business_no)
                level = merchant.level
                data['business_no'] = business_no
                data['merchant_name'] = merchant.name
                data['account'] = level.account
                data['level_name'] = level.name
            else:
                merchant = Merchant.objects.filter(merchantuser_id=obj.merchantuser_id).first()
                level = merchant.level
                data['business_no'] = merchant.wyfMerchantID
                data['merchant_name'] = merchant.name
                data['account'] = level.account
                data['level_name'] = level.name
        except:
            pass
        return data

    def get_mobile(self, obj):
        try:
            return obj.merchantuser.mobile
        except:
            return ''


class LuckyBagRecordRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    operate_type_str = serializers.CharField(source='get_operate_type_display', read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    cashactivitydata = serializers.SerializerMethodField(read_only=True)
    activitydata = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LuckyBagRecord
        fields = ['id', 'lucky_bag', 'operate_type_str', 'operate_type', 'create_time', 'lucky_bag_balance',
                  'mobile', 'merchantuser_id', 'cashactivitydata', 'activitydata']

    def get_mobile(self, obj):
        try:
            return obj.merchantuser.mobile
        except:
            return ''

    def get_cashactivitydata(self, obj):
        try:
            if obj.operate_type == 2:
                cashactivitydata = obj.cashactivitydata
                return CashActivityDataRetrieveModelSerializer(cashactivitydata).data
            else:
                return {}
        except:
            return {}

    def get_activitydata(self, obj):
        try:
            if obj.operate_type == 1:
                activitydata = obj.activitydata
                return LuckyBagChildActivityDataRetrieveModelSerializer(activitydata).data
            else:
                return {}
        except:
            return {}


class MerchantEnterQuestModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    file_status_str = serializers.CharField(source='get_file_status_display', read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEnterQuest
        fields = ['id', 'create_time', 'file', 'logs_file', 'file_status', 'file_status_str',
                  'total_line', 'success_line', 'error_line', 'remark', 'create_user']

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''


class ScoutTheStoreLeaderboardModelSerializer(serializers.ModelSerializer):

    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    creator = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ScoutTheStoreLeaderboard
        fields = ('city', 'merhant_name', 'likes', 'update_time', 'creator')

    def get_creator(self, obj):
        try:
            return json.loads(obj.creator.replace("'", '"'))
        except:
            return ['-']


class MerchantNFCDeviceTradeModelSerializer(serializers.ModelSerializer):

    trade_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantNFCDeviceTrade
        fields = ('id', 'sn', 'device_type', 'store_name', 'transaction_id', 'total_amount', 'trade_time', 'merchant')

    def get_merchant(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            merchant = obj.merchant
            if merchant:
                data['merchant_name'] = merchant.name
                data['business_no'] = merchant.wyfMerchantID
                level = merchant.level
                data['city_name'] = level.city_name
                data['district_name'] = level.district_name
                data['branch_name'] = level.branch_name
        except:
            pass
        return data


class MerchantListModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_mall_str = serializers.CharField(source='get_is_mall_display', read_only=True)
    applyment_state_str = serializers.CharField(source='get_applyment_state_display', read_only=True)
    verify_state_str = serializers.CharField(source='get_verify_state_display', read_only=True)
    is_enter_auth = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'level_name', 'subject_type_str', 'subject_type', 'name', 'wyfMerchantID', 'branch_num',
                  'order_num', 'settlement_amount', 'create_time', 'short_name', 'settlement_amount_by_day',
                  'is_mall', 'is_mall_str', 'applyment_state', 'applyment_state_str', 'verify_state', 'verify_state_str',
                  'is_enter_auth')

    def get_is_enter_auth(self, obj):
        if obj.is_mall == 0:
            if obj.channel_id != 3:
                return 0
            else:
                return 1
        else:
            return 0

    def get_level_name(self, obj):
        try:
            if obj.applyment_state in [1, 4]:
                mall_applyment = MerchantMallApplyment.objects.filter(merchant_id=obj.id, applyment_type=1).last()
                if mall_applyment:
                    if mall_applyment.applyment_state == 4:
                        result = check_sign_contract_result(obj.ruiyinxinMerchantID)
                        if result['data']['sign_status'] == 3:
                            obj.applyment_state = 1
                            obj.verify_state = 1
                            obj.save()
                            mall_applyment.applyment_state = 1
                            mall_applyment.audit_time = datetime.datetime.now()
                            mall_applyment.save()
                    elif mall_applyment.applyment_state == 1:
                        result = get_sign_contract_url(obj.ruiyinxinMerchantID)
                        if result['result_code'] != 'fail':
                            if result['data']['open_status'] == 2:
                                if not mall_applyment.sign_url:
                                    signUrl = result['data']['signUrl']
                                    sign_url = make_qrcode1(obj.ruiyinxinMerchantID, signUrl, key=None)
                                    mall_applyment.sign_url = sign_url
                                mall_applyment.applyment_state = 2
                                mall_applyment.save()
                                obj.applyment_state = 2
                                obj.save()
                            elif result['data']['open_status'] == 3:
                                mall_applyment.applyment_state = 3
                                mall_applyment.reject_reason = result['data']['open_result']
                                mall_applyment.save()
                                obj.applyment_state = 3
                                obj.save()
        except:
            pass
        try:
            return obj.level.name
        except:
            return ''


class MerchantImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantImage
        fields = ['id', 'image']


class MerchantChannelModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantChannel
        fields = ['id', 'smid', 'sub_mchid', 'channel_mchid', 'channel_id']


class MerchantRetrieveModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    business_category_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    close_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    merchantimage_set = MerchantImageSerializer(many=True)
    channel_name = serializers.SerializerMethodField(read_only=True)
    merchantchannel_set = MerchantChannelModelSerializer(many=True)
    mall_applyment = serializers.SerializerMethodField(read_only=True)
    is_enter_auth = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'level', 'subject_type_str', 'subject_type', 'name', 'wyfMerchantID', 'branch_num',
                  'order_num', 'settlement_amount', 'store_address', 'managerName', 'managermobile', 'account_name',
                  'account_bank', 'account_number', 'identification_number', 'create_time', 'store_header_copy',
                  'short_name', 'open_work_time', 'close_work_time', 'merchantimage_set', 'store_logo_copy', 'business_category_id',
                  'business_category_name', 'longitude', 'latitude', 'prov_name', 'city_name', 'district_name', 'prov_code',
                  'city_code', 'district_code', 'merchant_desc', 'is_online', 'channel_id', 'channel_name', 'merchantchannel_set',
                  'settlement_amount_by_day', 'mall_applyment', 'is_enter_auth')

    def get_is_enter_auth(self, obj):
        if obj.is_mall == 0:
            check_merhant_channel = MerchantChannel.objects.filter(merchant_id=obj.id, channel_id=3)
            if not check_merhant_channel:
                return 0
            else:
                return 1
        else:
            return 0

    def get_mall_applyment(self, obj):
        data = {}
        data['is_mall'] = obj.is_mall
        data['is_mall_str'] = obj.get_is_mall_display()
        data['create_time'] = ''
        data['contract'] = ''
        data['applyment_state'] = ''
        data['applyment_state_str'] = ''
        data['audit_time'] = ''
        data['verify_state'] = ''
        data['verify_state_str'] = ''
        data['verify_user'] = ''
        data['verify_time'] = ''
        data['sign_url'] = ''
        data['reject_reason'] = ''
        try:
            mall_applyment = MerchantMallApplyment.objects.filter(merchant_id=obj.id, applyment_type=1).last()
            if mall_applyment:
                data['reject_reason'] = mall_applyment.reject_reason
                data['create_time'] = mall_applyment.create_time.strftime("%Y-%m-%d %H:%M:%S")
                data['contract'] = mall_applyment.contract.url
                data['applyment_state'] = mall_applyment.applyment_state
                data['applyment_state_str'] = mall_applyment.get_applyment_state_display()
                data['verify_state'] = mall_applyment.verify_state
                data['verify_state_str'] = mall_applyment.get_verify_state_display()
                if mall_applyment.verify_user:
                    data['verify_user'] = mall_applyment.verify_user.nickname
                # if mall_applyment.applyment_state == 4:
                #     result = check_sign_contract_result(obj.ruiyinxinMerchantID)
                #     if result['data']['sign_status'] == 3:
                #         obj.applyment_state = 1
                #         obj.verify_state = 1
                #         obj.save()
                #         mall_applyment.applyment_state = 1
                #         mall_applyment.audit_time = datetime.datetime.now()
                #         mall_applyment.save()
                # elif mall_applyment.applyment_state == 1:
                #     result = get_sign_contract_url(obj.ruiyinxinMerchantID)
                #     if result['result_code'] != 'fail':
                #         if result['data']['open_status'] == 2:
                #             if not mall_applyment.sign_url:
                #                 signUrl = result['data']['sign_url']
                #                 sign_url = make_qrcode1(obj.ruiyinxinMerchantID, signUrl, key=None)
                #                 mall_applyment.sign_url = sign_url
                #             mall_applyment.applyment_state = 2
                #             mall_applyment.save()
                #             obj.applyment_state = 2
                #             obj.save()
                #         elif result['data']['open_status'] == 3:
                #             mall_applyment.applyment_state = 3
                #             mall_applyment.reject_reason = result['data']['open_result']
                #             mall_applyment.save()
                #             obj.applyment_state = 3
                #             obj.save()
                data['sign_url'] = mall_applyment.sign_url.url
                data['audit_time'] = mall_applyment.audit_time.strftime("%Y-%m-%d %H:%M:%S")
                data['verify_time'] = mall_applyment.verify_time.strftime("%Y-%m-%d %H:%M:%S")
        except:
            pass
        return data

    def get_business_category_name(self, obj):
        try:
            return obj.business_category.name
        except:
            return ''

    def get_channel_name(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class MerchantEnterModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    level = serializers.SerializerMethodField(read_only=True)
    manageruser = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEnter
        fields = ('id', 'create_time', 'level', 'manageruser')

    def get_manageruser(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class GoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)
    is_coupon_goods = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant', 'is_coupon_goods', 'order_species', 'order_species_str')

    def get_is_coupon_goods(self, obj):
        try:
            alidiscountcoupon_id = self.context.get('alidiscountcoupon_id', None)
            if alidiscountcoupon_id:
                check_available = AliDiscountCouponGoodsAvailable.objects.filter(goods_id=obj.id, alidiscountcoupon_id=alidiscountcoupon_id)
                if check_available:
                    return 1
                else:
                    return 0
            else:
                return 0
        except:
            return 0

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['name'] = ''
        data['short_name'] = ''
        data['id'] = ''
        try:
            merchant = obj.merchant
            data['name'] = merchant.name
            data['short_name'] = merchant.short_name
            data['id'] = merchant.id
        except:
            pass
        return data


class EnterLvelModelSerializer(serializers.ModelSerializer):

    contact = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Level
        fields = ['id', 'city_name', 'district_name', 'branch_name', 'account', 'contact']

    def get_contact(self, obj):
        data = {}
        merchant = self.context.get('merchant', None)
        data['managerName'] = merchant.managerName
        data['managermobile'] = merchant.managermobile
        try:
            enterlevel = MerchantEnter.objects.filter(level_id=obj.id, merchant_id=merchant.id).first()
            if enterlevel:
                data['managerName'] = enterlevel.managerName
                data['managermobile'] = enterlevel.managermobile
        except:
            pass
        return data


class MerchantMonthlyBillListModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model =  MerchantMonthlyBill
        fields = ('id', 'bill_name', 'bill_time', 'order_amount', 'order_count', 'separate_amount', 'restitution_amount', 'merchant', 'settlement_amount',
                  'merchant_id', 'merchant_name', 'level_name')

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class MerchantMonthlyBillRetrieveModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model =  MerchantMonthlyBill
        fields = ('id', 'bill_name', 'bill_time', 'order_amount', 'order_count', 'separate_amount', 'restitution_amount',
                  'settlement_amount', 'bill_file', 'merchant_id', 'merchant_name', 'level')

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class MerchantEightEightActivityModelSerializer(serializers.ModelSerializer):

    activity_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    level_name = serializers.SerializerMethodField(read_only=True)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    activity_status = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    new_prize = serializers.SerializerMethodField(read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)

    class Meta:
        model = MerchantEightEightActivity
        fields = ['id', 'activity_id', 'activity_name', 'activity_start_time', 'activity_end_time', 'activity_description', 'level_name',
                  'activity_status', 'activity_status_str', 'total_amount', 'total_count', 'activity_type', 'activity_type_str',
                  'new_prize', 'is_keguan', 'pushEventIds']

    def get_new_prize(self, obj):
        return 0

    def get_activity_type(self, obj):
        if obj.id == 47:
            return 1
        elif obj.id == 50:
            return 4
        else:
            return obj.activity_type

    def get_activity_status(self, obj):
        if obj.activity_status == 1:
            if obj.activity_start_time < datetime.datetime.now():
                obj.activity_status = 2
                obj.save()
        elif obj.activity_status == 2:
            if obj.activity_end_time < datetime.datetime.now():
                obj.activity_status = 3
                obj.save()
        return obj.activity_status

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class MerchantEightEightWhiteTableModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightWhiteTable
        fields = ['id', 'merchant', 'business_no']

    def get_merchant(self, obj):
        data = {}
        data['subject_type_str'] = ''
        data['subject_type'] = ''
        data['merchant_id'] = ''
        data['name'] = ''
        data['level_name'] = ''
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            if merchant:
                data['subject_type_str'] = merchant.get_subject_type_display()
                data['subject_type'] = merchant.subject_type
                data['merchant_id'] = merchant.id
                data['name'] = merchant.name
                data['level_name'] = merchant.level.name
        except:
            pass
        return data


class MerchantEightEightActivityOrderModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)
    is_standard = serializers.SerializerMethodField(read_only=True)
    trade_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)

    class Meta:
        model = MerchantEightEightActivityOrder
        fields = ['id', 'merchant', 'business_no', 'is_standard', 'trade_amount', 'trade_time']

    def get_merchant(self, obj):
        data = {}
        data['subject_type_str'] = ''
        data['subject_type'] = ''
        data['merchant_id'] = ''
        data['name'] = ''
        data['level_name'] = ''
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            if merchant:
                data['subject_type_str'] = merchant.get_subject_type_display()
                data['subject_type'] = merchant.subject_type
                data['merchant_id'] = merchant.id
                data['name'] = merchant.name
                data['level_name'] = merchant.level.name
        except:
            pass
        return data

    def get_is_standard(self, obj):
        if obj.is_standard == 2:
            return 1
        return obj.is_standard


class MerchantEightEightActivityPrizeModelSerializer(serializers.ModelSerializer):

    prize_type_str = serializers.CharField(source='get_prize_type_display', read_only=True)

    class Meta:
        model = MerchantEightEightActivityPrize
        fields = ['id', 'prize_type', 'amount', 'prize_name', 'count', 'prize_type_str', 'second_count']


class MerchantBusinessQRCodeVisitListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    customeruservice = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCodeVisit
        fields = ['id', 'create_time', 'customeruservice']

    def get_customeruservice(self, obj):
        data = {}
        data['realname'] = ''
        data['mobile'] = ''
        data['openid'] = ''
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                data['realname'] = customeruservice.username
                data['mobile'] = customeruservice.mobile
                data['openid'] = customeruservice.wyh_openid
        except:
            pass
        return data


class MerchantBusinessQRCodeListModelSerializer(serializers.ModelSerializer):

    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)
    is_c_bind_str = serializers.CharField(source='get_is_c_bind_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    c_bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCode
        fields = ['id', 'sn', 'is_bind', 'is_bind_str', 'bind_time', 'merchant', 'inviter_count', 'inviter_total_count',
                  'is_c_bind', 'is_c_bind_str', 'c_bind_time']

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            merchant = obj.merchant
            if merchant:
                level = merchant.level
                data['merchant_id'] = merchant.id
                data['business_no'] = merchant.wyfMerchantID
                data['merchant_name'] = merchant.name
                data['city_name'] = level.city_name
                data['district_name'] = level.district_name
                data['branch_name'] = level.branch_name
        except:
            pass
        return data


class MerchantBusinessQRCodeRetrieveModelSerializer(serializers.ModelSerializer):

    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)
    is_c_bind_str = serializers.CharField(source='get_is_c_bind_display', read_only=True)
    is_achieve_str = serializers.CharField(source='get_is_achieve_display', read_only=True)
    award_status_str = serializers.CharField(source='get_award_status_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    award_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    c_bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)
    manager = serializers.SerializerMethodField(read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    cashactivitydata = serializers.SerializerMethodField(read_only=True)
    sn_qrcode = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCode
        fields = ['id', 'sn', 'is_bind', 'is_bind_str', 'bind_time', 'merchant', 'manager', 'is_c_bind', 'is_c_bind_str', 'c_bind_time', 'customeruservice',
                  'award_status', 'award_status_str', 'is_achieve', 'is_achieve_str', 'award_time', 'cashactivitydata', 'sn_qrcode']

    def get_sn_qrcode(self, obj):
        try:
            if not obj.sn_qrcode:
                sn_url = f'https://qrcode.sutpay.com/business/business_district/?shop_id={obj.sn}'
                # sn_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                sn_qrcode = make_qrcode4(obj.sn, sn_url, None)
                obj.sn_url = sn_url
                obj.sn_qrcode = sn_qrcode
                obj.save()
                return f'https://circle.sutpay.cn/{sn_qrcode}'
            else:
                return obj.sn_qrcode.url
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            merchant = obj.merchant
            if merchant:
                level = merchant.level
                data['merchant_id'] = merchant.id
                data['business_no'] = merchant.wyfMerchantID
                data['merchant_name'] = merchant.name
                data['city_name'] = level.city_name
                data['district_name'] = level.district_name
                data['branch_name'] = level.branch_name
        except:
            pass
        return data

    def get_manager(self, obj):
        try:
            user = obj.user
            if user:
                return f'{user.nickname}({user.mobile})'.replace('None', '')
            else:
                return ''
        except:
            return ''

    def get_customeruservice(self, obj):
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                return f'{customeruservice.realname}({customeruservice.mobile})'.replace('None', '')
            else:
                return ''
        except:
            return ''

    def get_cashactivitydata(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['received_time'] = ''
        data['amount'] = ''
        try:
            cashactivitydata = obj.cashactivitydata
            if cashactivitydata:
                cash_activity = cashactivitydata.cash_activity
                data['id'] = cashactivitydata.id
                data['activity_name'] = cash_activity.name
                data['amount'] =  cashactivitydata.amount
                data['state'] = cashactivitydata.state
                data['received_time'] = cashactivitydata.received_time.strftime("%Y-%m-%d %H:%M:%S")
            else:
                if obj.is_bind == 1:
                    companyuser = obj.user
                    companyuser_id = companyuser.id
                    date_now = datetime.datetime.now()
                    nonce_str = random_str()
                    cash_activity_id = 355
                    amount = Decimal('5')
                    cash_activity = CashActivity.objects.get(id=cash_activity_id)
                    cashactivitydata_data = {}
                    cashactivitydata_data['companyuser_id'] = companyuser_id
                    cashactivitydata_data['cash_activity_id'] = cash_activity.id
                    cashactivitydata_data['amount'] = amount
                    cashactivitydata_data['create_time'] = date_now
                    cashactivitydata_data['nonce_str'] = nonce_str
                    cashactivitydata_data['desc'] = cash_activity.name
                    cashactivitydata_data['mobile'] = companyuser.mobile
                    cashactivitydata_data['openid'] = companyuser.openid
                    cashactivitydata_data['appid'] = 'wxb67b94c00d7cd83f'
                    cashactivitydata_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % companyuser_id}'
                    cashactivitydata = CashActivityData.objects.create(**cashactivitydata_data)
                    while True:
                        activity = CashActivity.objects.get(id=cash_activity_id)
                        activity_origin_take_amount = activity.take_amount
                        activity_origin_remain_amount = activity.remain_amount
                        activity_new_take_amount = activity_origin_take_amount + amount
                        activity_new_remain_amount = activity_origin_remain_amount - amount
                        result = CashActivity.objects.filter(take_amount=activity_origin_take_amount,
                                                             remain_amount=activity_origin_remain_amount,
                                                             id=cash_activity_id).update(
                            take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                        if result == 0:
                            continue
                        break
                    obj.cashactivitydata_id = cashactivitydata.id
                    # obj.is_achieve = 1
                    # obj.award_time = CustomerUserViceInviterRecord.objects.filter(qrcode_id=obj.id, is_inviter=1)[1].inviter_time
                    obj.save()
                    data['id'] = cashactivitydata.id
                    data['activity_name'] = cash_activity.name
                    data['amount'] = cashactivitydata.amount
                    data['state'] = cashactivitydata.state
                    data['received_time'] = cashactivitydata.received_time.strftime("%Y-%m-%d %H:%M:%S")
        except:
            pass
        return data


class MerchantEightEightDrawListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightDraw
        fields = ['id', 'create_time', 'amount', 'received_time', 'state', 'state_str', 'business_no', 'level_name', 'mobile',
                  'merchant', 'index']

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            data['merchant_id'] = merchant.id
            data['merchant_short_name'] = merchant.short_name
        except:
            pass
        return data

    def get_amount(self, obj):
        try:
            prize = MerchantEightEightActivityPrize.objects.get(id=obj.win_type)
            if prize.prize_type == 1:
                return f'¥{obj.amount}'
            else:
                return prize.prize_name
            # if obj.win_type == 6:
            #     return '谢谢参与'
            # else:
            #     return f'¥{obj.amount}'
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return obj.merchantuser.mobile
        except:
            return ''

#商户达标奖-客管推送记录
class MerchantEightEightDrawKeGuanListModelSerializer(serializers.ModelSerializer):
    push_status_str = serializers.CharField(source='get_push_status_display', read_only=True)
    push_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_no = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightDrawKeguan
        fields = ['id', 'push_status_str', 'push_status', 'push_time', 'return_msg', 'draw_id',
                  'payment_no']

    def get_payment_no(self, obj):
        try:
            return obj.draw.payment_no
        except:
            return ''


class AliDiscountCouponInfoListModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_distributed = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    coupon_type = serializers.SerializerMethodField(read_only=True)
    coupon_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'gmt_distributed', 'customeruser_realname', 'companyuser_nickname', 'activity_name',
                  'coupon_type', 'coupon_type_str', 'level_name', 'return_msg']

    def get_mobile(self, obj):
        if obj.alidiscountcoupon.coupon_way == 5 and obj.alidiscountcoupon.coupon_channel == 1:
            return obj.login_id
        else:
            return obj.mobile

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_coupon_type_str(self, obj):
        try:
            return obj.alidiscountcoupon.get_coupon_type_display()
        except:
            return ''

    def get_coupon_type(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_type
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.alidiscountcoupon.activity_name
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            return obj.customer_user.realname
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''


class MerchantEightEightDrawRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    alidiscountcouponinfo_list = serializers.SerializerMethodField(read_only=True)
    channel = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightDraw
        fields = ['id', 'create_time', 'amount', 'received_time', 'state', 'state_str', 'business_no', 'level',
                  'login_id', 'realname', 'mobile', 'payment_no', 'mobile', 'merchant', 'return_msg', 'activity_name',
                  'alidiscountcouponinfo_list', 'channel']

    def get_channel(self, obj):
        try:
            return f'{obj.channel.name}({obj.channel.mchid})'
        except:
            return ''

    def get_alidiscountcouponinfo_list(self, obj):
        try:
            alidiscountcouponinfo_list = obj.alidiscountcouponinfo_list
            if alidiscountcouponinfo_list:
                queryset = AliDiscountCouponInfo.objects.filter(id__in=json.loads(alidiscountcouponinfo_list))
                return AliDiscountCouponInfoListModelSerializer(queryset, many=True).data
            return []
        except:
            return []

    def get_activity_name(self, obj):
        return '深圳达标商户有礼'

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            data['merchant_id'] = merchant.id
            data['merchant_short_name'] = merchant.short_name
        except:
            pass
        return data

    def get_amount(self, obj):
        try:
            prize = MerchantEightEightActivityPrize.objects.get(id=obj.win_type)
            if prize.prize_type == 1:
                return f'¥{obj.amount}'
            else:
                return prize.prize_name
            # if obj.win_type == 6:
            #     return '谢谢参与'
            # else:
            #     return f'¥{obj.amount}'
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data

    def get_mobile(self, obj):
        try:
            return obj.merchantuser.mobile
        except:
            return ''


class MerchantBillListModelSerializer(serializers.ModelSerializer):

    receipts_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    bill_state_str = serializers.CharField(source='get_bill_state_display', read_only=True)
    bill_type_str = serializers.CharField(source='get_bill_type_display', read_only=True)
    merchant_info = serializers.SerializerMethodField(read_only=True)
    account_info = serializers.SerializerMethodField(read_only=True)
    week_day = serializers.SerializerMethodField(read_only=True)
    order_count = serializers.SerializerMethodField(read_only=True)
    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    channel_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBill
        fields = ['id', 'receipts_time', 'bill_state', 'bill_state_str', 'merchant_info', 'payable_amount', 'account_info', 'settlement_time', 'week_day',
                  'order_count', 'channel_id', 'channel_name', 'bill_type', 'bill_type_str']

    def get_channel_name(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_order_count(self, obj):
        try:
            return obj.orderinfo_set.all().count()
        except:
            return 0

    def get_week_day(self, obj):
        week_day_dict = {
            0: '星期一',
            1: '星期二',
            2: '星期三',
            3: '星期四',
            4: '星期五',
            5: '星期六',
            6: '星期日',
        }
        day = obj.receipts_time.weekday()
        return week_day_dict[day]

    def get_merchant_info(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['wyfMerchantID'] = ''
        data['level_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['merchant_id'] = ''
        try:
            merchant = obj.merchant
            level = merchant.level
            data['merchant_name'] = merchant.name
            data['wyfMerchantID'] = merchant.wyfMerchantID
            data['level_name'] = level.name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['merchant_id'] = merchant.id
        except:
            pass
        return data

    def get_account_info(self, obj):
        data = {}
        data['account_number'] = ''
        data['account_bank'] = ''
        data['account_name'] = ''
        try:
            bill_state = obj.bill_state
            if bill_state == 1:
                data['account_number'] = str(obj.merchant.account_number)[:6] + '********' + str(obj.merchant.account_number)[-5:]
                data['account_bank'] = obj.merchant.account_bank
                data['account_name'] = obj.merchant.account_name
            else:
                data['account_number'] = obj.account_number
                data['account_bank'] = obj.account_bank
                data['account_name'] = obj.account_name
        except:
            pass
        return data


class MerchantBillRetrieveModelSerializer(serializers.ModelSerializer):

    receipts_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    bill_state_str = serializers.CharField(source='get_bill_state_display', read_only=True)
    merchant_info = serializers.SerializerMethodField(read_only=True)
    order_count = serializers.SerializerMethodField(read_only=True)
    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    account_info = serializers.SerializerMethodField(read_only=True)
    # payable_amount = serializers.SerializerMethodField(read_only=True)
    settlement_info = serializers.SerializerMethodField(read_only=True)
    fail_reason = serializers.SerializerMethodField(read_only=True)
    bill_type_str = serializers.CharField(source='get_bill_type_display', read_only=True)
    other_amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBill
        fields = ['id', 'receipts_time', 'bill_state', 'bill_state_str', 'merchant_info', 'payable_amount', 'settlement_time', 'order_count', 'account_info',
                  'settlement_info', 'fail_reason', 'bill_type', 'bill_type_str', 'commission', 'amount', 'other_amount', 'other_commission', 'other_settlement_amount']

    def get_other_amount(self, obj):
        try:
            yesterday = datetime.datetime.now() + datetime.timedelta(days=-1)
            if obj.other_amount == None and obj.receipts_time < yesterday:
                url = 'https://manage.gdwxyf.com/internal/searchorders.do'
                body = {
                    "shopId": obj.merchant.wyfMerchantID,
                    "start": obj.receipts_time.strftime("%Y-%m-%d 00:00:00"),
                    "end": obj.receipts_time.strftime("%Y-%m-%d 23:59:59"),
                    "branchId": "2",
                    "account": "gdyouzheng",
                    "orderStatus": "all"
                }
                response = requests.post(url=url, data=body)
                result = response.json()['showList']
                other_amount = Decimal('0')
                other_commission = Decimal('0')
                other_settlement_amount = Decimal('0')
                for i in result:
                    if 'subOpenid' in i:
                        if 'omjwf4' != i['subOpenid'][:6]:
                            other_amount += Decimal(i['totalFee'])
                            other_commission += Decimal(i['commissionPay'])
                            other_settlement_amount += Decimal(i['paidout'])
                    else:
                        if i['device'] != '微邮惠商圈':
                            other_amount += Decimal(i['totalFee'])
                            other_commission += Decimal(i['commissionPay'])
                            other_settlement_amount += Decimal(i['paidout'])
                obj.other_amount = other_amount
                obj.other_commission = other_commission
                obj.other_settlement_amount = other_settlement_amount
                obj.save()
                return obj.other_amount
            else:
                return obj.other_amount
        except:
            return ''

    def get_fail_reason(self, obj):
        return ''

    def get_settlement_info(self, obj):
        data = []
        try:
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                merchantsettlementrecord_data = {}
                merchantsettlementrecord = merchantbillsettlementrecord.settlement_record
                merchantsettlementrecord_data['settlement_time'] = merchantsettlementrecord.settlement_time.strftime('%Y-%m-%d')
                merchantsettlementrecord_data['settlement_id'] = merchantsettlementrecord.id
                merchantsettlementrecord_data['settlement_amount'] = merchantsettlementrecord.amount
                merchantsettlementrecord_data['status'] = merchantsettlementrecord.status
                merchantsettlementrecord_data['status_str'] = merchantsettlementrecord.get_status_display()
                data.append(merchantsettlementrecord_data)
        except:
            pass
        return data

    # def get_payable_amount(self, obj):
    #     try:
    #         bill_state = obj.bill_state
    #         if bill_state == 3:
    #             return obj.settlement_record.amount
    #         else:
    #             return 0
    #     except:
    #         return 0

    def get_merchant_info(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['wyfMerchantID'] = ''
        data['level'] = ''
        data['merchant_id'] = ''
        try:
            data['merchant_name'] = obj.merchant.name
            data['wyfMerchantID'] = obj.merchant.wyfMerchantID
            data['merchant_id'] = obj.merchant_id
            level = obj.merchant.level
            data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
        except:
            pass
        return data

    def get_order_count(self, obj):
        try:
            return obj.orderinfo_set.all().count()
        except:
            return 0

    def get_account_info(self, obj):
        data = {}
        data['account_number'] = ''
        data['account_bank'] = ''
        data['account_name'] = ''
        try:
            bill_state = obj.bill_state
            if bill_state == 1:
                data['account_number'] = str(obj.merchant.account_number)[:6] + '********' + str(obj.merchant.account_number)[-5:]
                data['account_bank'] = obj.merchant.account_bank
                data['account_name'] = obj.merchant.account_name
            else:
                data['account_number'] = obj.account_number
                data['account_bank'] = obj.account_bank
                data['account_name'] = obj.account_name
        except:
            pass
        return data


class MerchantBusinessCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantBusinessCategory
        fields = ['id', 'name']


class WaivePaymentActivityModelSerializer(serializers.ModelSerializer):

    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    is_repeat_str = serializers.CharField(source='get_is_repeat_display', read_only=True)
    activity_state = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = WaivePaymentActivity
        fields = ['id', 'activity_name', 'available_begin_time', 'available_end_time', 'desc', 'activity_state', 'activity_state_str', 'description',
                  'receive_amount', 'join_number', 'create_time', 'is_repeat', 'is_repeat_str', 'is_keguan', 'pushEventIds']

    def get_activity_state(self, obj):
        try:
            available_end_time = obj.available_end_time
            if available_end_time < datetime.datetime.now():
                obj.activity_state = 4
                obj.save()
            return obj.activity_state
        except:
            return obj.activity_state


class WaivePaymentAdvanceModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    payment_state_str = serializers.CharField(source='get_payment_state_display', read_only=True)
    operate_type_str = serializers.CharField(source='get_operate_type_display', read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)
    activate_user = serializers.SerializerMethodField(read_only=True)
    trade_time_begin = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    trade_time_end = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activate_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = WaivePaymentAdvance
        fields = ['id', 'create_time', 'activity_state', 'activity_state_str', 'remark',
                  'file', 'create_user', 'payment_state', 'payment_state_str', 'trade_time_begin',
                  'trade_time_end', 'activate_time', 'activate_user', 'name', 'operate_type', 'operate_type_str',
                  'join_number']

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''

    def get_activate_user(self, obj):
        try:
            return obj.activate_user.nickname
        except:
            return ''
#月月邮免单-客管推送记录
class WaiVePaymentKeGuanListModelSerializer(serializers.ModelSerializer):
    push_status_str = serializers.CharField(source='get_push_status_display', read_only=True)
    push_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_no = serializers.SerializerMethodField(read_only=True)
    merchant_id = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = WaivePaymentMerchantKeguan
        fields = ['id', 'push_status_str', 'push_status', 'push_time', 'return_msg', 'payment_id',
                  'payment_no','merchant_id']

    def get_merchant_id(self, obj):
        try:
            return obj.payment.merchant.id
        except:
            return ''

    def get_payment_no(self, obj):
        try:
            return obj.payment.payment_no
        except:
            return ''



class WaivePaymentMerchantInfoModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ['id', 'short_name', 'level']

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class WaivePaymentMerchantListModelSerializer(serializers.ModelSerializer):

    # create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_state_str = serializers.CharField(source='get_payment_state_display', read_only=True)
    # received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = WaivePaymentMerchantInfoModelSerializer()
    # amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = WaivePaymentMerchant
        fields = ['id', 'business_no', 'payment_state', 'payment_state_str', 'company_mobile', 'amount', 'merchant']

    # def get_amount(self, obj):
    #     try:
    #         if obj.payment_state in [1, 2, 3]:
    #             return obj.amount
    #         return ''
    #     except:
    #         return ''


class WaivePaymentMerchantRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_state_str = serializers.CharField(source='get_payment_state_display', read_only=True)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    available_time = serializers.SerializerMethodField(read_only=True)
    merchant = WaivePaymentMerchantInfoModelSerializer()

    class Meta:
        model = WaivePaymentMerchant
        fields = ['id', 'create_time', 'business_no', 'payment_state', 'payment_state_str', 'company_mobile',
                  'received_time', 'payment_no', 'return_msg', 'partner_trade_no', 'account', 'name', 'payment_time',
                  'amount', 'merchant', 'activity_name', 'available_time']

    def get_activity_name(self, obj):
        try:
            return obj.waivepaymentactivity.activity_name
        except:
            return ''

    def get_available_time(self, obj):
        try:
            return f'{obj.waivepaymentactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.waivepaymentactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''

    # def get_amount(self, obj):
    #     try:
    #         if obj.payment_state in [1, 2, 3]:
    #             return obj.amount
    #         return ''
    #     except:
    #         return ''


class WaivePaymentOrderModelSerializer(serializers.ModelSerializer):

    trade_time_end = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    trade_type_str = serializers.CharField(source='get_trade_type_display', read_only=True)
    is_hit_str = serializers.CharField(source='get_is_hit_display', read_only=True)

    class Meta:
        model = WaivePaymentOrder
        fields = ['id', 'order_no', 'trade_no', 'trade_type', 'trade_type_str', 'rate_money',
                  'trade_money', 'settlement_money', 'trade_time_end', 'channel', 'is_hit', 'is_hit_str']


class MerchantSettlementRecordListModelSerializer(serializers.ModelSerializer):

    settlement_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    channel = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    receipts_time = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)

    class Meta:
        model = MerchantSettlementRecord
        fields = ['id', 'settlement_time', 'channel', 'channel_id', 'status', 'status_str', 'amount', 'receipts_time', 'merchant', 'level_name', 'is_bind',
                  'is_bind_str']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = obj.merchant
            data['merchant_name'] = merchant.name
            data['merchant_id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
        except:
            pass
        return data

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_receipts_time(self, obj):
        data = ''
        try:
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                data += f"{merchantbillsettlementrecord.bill.receipts_time.strftime('%Y-%m-%d')},"
        except:
            pass
        if ',' in data:
            data = data[:-1]
        return data


class MerchantSettlementRecordRetrieveModelSerializer(serializers.ModelSerializer):

    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    channel = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    receipts_data = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)

    class Meta:
        model = MerchantSettlementRecord
        fields = ['id', 'settlement_time', 'channel', 'channel_id', 'status', 'status_str', 'amount', 'receipts_data', 'merchant', 'level_name',
                  'account_name', 'account_bank', 'account_number', 'fail_reason', 'is_bind', 'is_bind_str']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = obj.merchant
            level = merchant.level
            data['merchant_name'] = merchant.name
            data['merchant_id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
            data['level'] =  f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
        except:
            pass
        return data

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_receipts_data(self, obj):
        data = {}
        try:
            bill_list = []
            time_str = ''
            order_num = 0
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                bill_data = {}
                bill = merchantbillsettlementrecord.bill
                receipts_time = bill.receipts_time.strftime('%Y-%m-%d')
                time_str += f"{receipts_time},"
                orderinfo_set = bill.orderinfo_set.all()
                if orderinfo_set:
                    order_sum = orderinfo_set.count()
                    payable_settled_amount__sum = orderinfo_set.aggregate(Sum('payable_settled_amount'))['payable_settled_amount__sum']
                    order_num += order_sum
                    bill_data['order_count'] = order_sum
                    bill_data['payable_settled_amount__sum'] = payable_settled_amount__sum
                    bill_data['receipts_time'] = receipts_time
                    bill_data['bill_id'] = bill.id
                    bill_list.append(bill_data)
            if ',' in time_str:
                time_str = time_str[:-1]
            data['receipts_time'] = time_str
            data['order_count'] = order_num
            data['array'] = bill_list
        except:
            pass
        return data


class MerchantBankQRCodeQuestModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    file_type_str = serializers.CharField(source='get_file_type_display', read_only=True)
    file_status_str = serializers.CharField(source='get_file_status_display', read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBankQRCodeQuest
        fields = ['id', 'create_time', 'file', 'logs_file', 'file_type', 'file_type_str', 'file_status', 'file_status_str',
                  'total_line', 'success_line', 'error_line', 'remark', 'create_user']

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''


class MerchantBankQRCodeListModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)
    is_download_str = serializers.CharField(source='get_is_download_display', read_only=True)

    class Meta:
        model = MerchantBankQRCode
        fields = ['id', 'merchant', 'code_id', 'link', 'is_download', 'is_download_str', 'visit', 'total_number', 'total_first_number']

    def get_merchant(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['prov_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['account_nine'] = ''
        try:
            merchant = obj.merchant
            level = obj.level
            data['id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account_nine'] = level.account_nine
        except:
            pass
        return data


class MerchantBankQRCodeRetrieveModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)
    qrcode = serializers.SerializerMethodField(read_only=True)
    bind_number = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.SerializerMethodField(read_only=True)
    is_download_str = serializers.CharField(source='get_is_download_display', read_only=True)

    class Meta:
        model = MerchantBankQRCode
        fields = ['id', 'merchant', 'code_id', 'qrcode', 'link', 'bind_number', 'parent_code_id', 'is_download', 'is_download_str', 'visit', 'create_time',
                  'total_number', 'total_first_number']

    def get_create_time(self, obj):
        try:
            return obj.quest.create_time.strftime("%Y-%m-%d %H:%M:%S")
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['prov_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['account_nine'] = ''
        try:
            merchant = obj.merchant
            level = obj.level
            data['id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account_nine'] = level.account_nine
        except:
            pass
        return data

    def get_qrcode(self, obj):
        try:
            if not obj.qrcode:
                link = obj.link
                url = 'https://partner.douyinpay.com/api/merchant/getBankSubQrCodeValue'
                body = {
                    "code_id": obj.code_id,
                    "sign": link.replace(f'https://partner.douyinpay.com/external/bankcode?code_id={obj.code_id}&sign=', '')
                }
                response = requests.post(url=url, json=body)
                result = response.json()
                code_url = result['code_url']
                parent_code_id = result['parent_code_id']
                qrcode = make_qrcode5(obj.code_id, code_url, None)
                obj.qrcode = qrcode
                obj.parent_code_id = parent_code_id
                obj.save()
                return f'https://circle.sutpay.cn/{qrcode}'
            else:
                return obj.qrcode.url
        except:
            return ''

    def get_bind_number(self, obj):
        data = {}
        data['total_number'] = 0
        data['total_first_number'] = 0
        data['last_month_number'] = 0
        data['last_month_first_number'] = 0
        data['this_month_number'] = 0
        data['this_month_first_number'] = 0
        data['yesterday_number'] = 0
        data['yesterday_first_number'] = 0
        try:
            today = datetime.datetime.now()
            yesterday = today + datetime.timedelta(-1)
            yesterday_begin = yesterday.strftime("%Y-%m-%d 00:00:00")
            yesterday_end = yesterday.strftime("%Y-%m-%d 23:59:59")
            last_month_begin = (today.replace(day=1) + datetime.timedelta(-1)).replace(day=1).strftime("%Y-%m-%d 00:00:00")
            last_month_end = (today.replace(day=1) + datetime.timedelta(-1)).strftime("%Y-%m-%d 23:59:59")
            this_month_begin = today.replace(day=1).strftime("%Y-%m-%d 00:00:00")
            this_month_end = today.strftime("%Y-%m-%d 23:59:59")
            total_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id).count()
            total_first_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, is_first=1).count()
            last_month_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, bind_time__gte=last_month_begin, bind_time__lte=last_month_end).count()
            last_month_first_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, is_first=1, bind_time__gte=last_month_begin, bind_time__lte=last_month_end).count()
            this_month_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, bind_time__gte=this_month_begin, bind_time__lte=this_month_end).count()
            this_month_first_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, is_first=1, bind_time__gte=this_month_begin, bind_time__lte=this_month_end).count()
            yesterday_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, bind_time__gte=yesterday_begin, bind_time__lte=yesterday_end).count()
            yesterday_first_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, is_first=1, bind_time__gte=yesterday_begin, bind_time__lte=yesterday_end).count()
            data['total_number'] = total_number
            data['total_first_number'] = total_first_number
            data['last_month_number'] = last_month_number
            data['last_month_first_number'] = last_month_first_number
            data['this_month_number'] = this_month_number
            data['this_month_first_number'] = this_month_first_number
            data['yesterday_number'] = yesterday_number
            data['yesterday_first_number'] = yesterday_first_number
        except:
            pass
        return data


class MerchantBankQRCodeBindDataListModelSerializer(serializers.ModelSerializer):

    is_first_str = serializers.CharField(source='get_is_first_display', read_only=True)
    card_type_str = serializers.CharField(source='get_card_type_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBankQRCodeBindData
        fields = ['id', 'code_id', 'card_number', 'is_first', 'is_first_str', 'card_type', 'card_type_str', 'bind_time', 'merchant']

    def get_merchant(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['account_nine'] = ''
        try:
            merchant = obj.merchant
            level = obj.level
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account_nine'] = level.account_nine
        except:
            pass
        return data


class MErchantBankQPCodeStatisticsListModelSerializer(serializers.ModelSerializer):

    bind_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MErchantBankQPCodeStatistics
        fields = ['id', 'code_id', 'bind_time', 'merchant', 'total_number', 'total_first_number']

    def get_merchant(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['account_nine'] = ''
        try:
            merchant = obj.merchant
            level = obj.level
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account_nine'] = level.account_nine
        except:
            pass
        return data